var mongoose = require('mongoose')
var TileSchema = require('../models/tile')

module.exports.downloadTile = function(req, res) {
  var tileset_id = req.params.tileset_id
  var z = +req.params.z || 0
  var x = +req.params.x || 0
  var y = +req.params.y || 0

  var tiles = 'tiles_' + tileset_id
  var Tile = mongoose.model(tiles, TileSchema, tiles)

  Tile.findOne({
    zoom_level: z,
    tile_column: x,
    tile_row: y
  }, function(err, tile) {
    if (err) {
      return res.status(500).json({ error: err })
    }

    if (!tile || !tile.tile_data) {
      return res.sendStatus(404)
    }

    res.set('Expires', new Date(Date.now() + 604800000).toUTCString())
    res.set(tiletype.headers(tile.tile_data))
    res.send(tile.tile_data)
  })
}